package com.t235.gc.auth.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.t235.gc.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${sso.redirect-uri}")
    private String ssoRedirectUri;

    @Autowired
    UserService userService;
    /**
     * 密码编码器
     *
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(10);
    }
    /**
     * 认证管理器
     *
     * @return
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //定义内存中的用户名密码与访问权限
        auth.userDetailsService(userService);//每次用户登入的时候就会调用到userService中的loadUserByUsername(Username)方法
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 安全拦截机制（最重要）
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //http.headers()//请求头设置
                //.frameOptions();//允许嵌套页面
        http
                .authorizeRequests()
                .antMatchers("/oauth2/authorization/github").permitAll()
                .antMatchers("/social/**","/users/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/custom/login")
                .loginProcessingUrl("/login")
                .successHandler(new SavedRequestAwareAuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                                        Authentication authentication) throws ServletException, IOException {
                        //super.onAuthenticationSuccess(request, response, authentication);
                        System.out.println("sso登录成功，重定向到前端服务器页面");
                        //request.getRequestDispatcher(ssoRedirectUri).forward(request,response);
                        response.sendRedirect(ssoRedirectUri);
                       /* Object principal=authentication.getPrincipal();
                        //resp.setContentType("application/json;charset=utf-8");
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out = response.getWriter();
                        response.setStatus(200);
                        Map<String,Object> map=new HashMap<>();
                        map.put("status",200);
                        map.put("msg","首页");
                        ObjectMapper om=new ObjectMapper();
                        //resp.sendRedirect("/index");
                        out.print(om.writeValueAsString(map));
                        out.flush();
                        out.close();*/
                    }
                })
                .permitAll()
                .and()
                .cors()
                .and()
                .csrf()
                .disable();
                //.and().addFilterBefore(new WebSecurityCorsFilter(), ChannelProcessingFilter.class);
        //自定义登录成功的页面地址
        //.successForwardUrl("/login-success");
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/js/**","/css/**","/assets/**","/fonts/**");
        web.ignoring().antMatchers("/oauth/check_token","/favicon.ico");
    }
}
